package com.studyweb.controller;

import com.studyweb.pojo.vo.Result;
import com.studyweb.service.QuestionImportService;
import com.studyweb.service.impl.ImportResultException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/questions")
public class QuestionImportController {

    @Autowired
    private QuestionImportService questionImportService;

    @PostMapping("/import")
    public Result<?> importQuestions(
            @RequestParam("file") MultipartFile file,
            @RequestHeader("X-Module-Type") String moduleType,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String subCategory,
            HttpServletRequest request) {
        try {
            // 从拦截器设置的request attribute中获取用户ID
            Long userId = (Long) request.getAttribute("userId");
            int importedCount = questionImportService.importQuestionsFromExcel(file, moduleType, category, subCategory, userId);
            return Result.success("题目导入成功", importedCount);
        } catch (ImportResultException ire) {
            // 处理我们自定义的导入结果异常，返回详细的导入结果信息
            log.info("导入完成: {}", ire.getMessage());
            return Result.success(ire.getMessage(), ire.getImportedCount());
        } catch (Exception e) {
            log.error("导入题目失败: {}", e.getMessage(), e);
            return Result.error("导入失败: " + e.getMessage());
        }
    }

    @GetMapping("/template")
    public ResponseEntity<byte[]> downloadTemplate() {
        try {
            ClassPathResource resource = new ClassPathResource("templates/question_import_template.xlsx");
            byte[] templateBytes = resource.getInputStream().readAllBytes();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            
            // 使用 RFC 5987 编码格式处理中文文件名
            String encodedFilename = "filename*=UTF-8''" + java.net.URLEncoder.encode("题目导入模板.xlsx", "UTF-8").replace("+", "%20");
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; " + encodedFilename);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(templateBytes);
        } catch (IOException e) {
            log.error("下载模板失败: {}", e.getMessage(), e);
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/export")
    public void exportQuestions(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String difficulty,
            @RequestParam(required = false) String questionType,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String subCategory,
            HttpServletResponse response) {
        try {
            log.info("接收到导出请求，参数: keyword={}, difficulty={}, questionType={}, module={}, category={}, subCategory={}", 
                     keyword, difficulty, questionType, module, category, subCategory);
            // 调用导出服务
            questionImportService.exportQuestionsToExcel(keyword, difficulty, questionType, module, category, subCategory, response);
        } catch (Exception e) {
            log.error("导出题目失败: {}", e.getMessage(), e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (IOException ioException) {
                log.error("写入响应失败: {}", ioException.getMessage(), ioException);
            }
        }
    }
}